import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Dispatch } from "redux";
import { User_dao } from "../component/SelectUser";
import ajax, { AxiosResponse } from "axios";
import { PostStatus } from "./postSlice";

export interface UserState {
    status: PostStatus;
    message: string | null;
    list: User_dao[];
}

const initialState: UserState = {
    status: PostStatus.idle,
    message: null,
    list: [],
};

export const postSlice = createSlice({
    name: "users",
    initialState,
    reducers: {
        userStatus: (
            state: any,
            action: PayloadAction<{
                status: PostStatus;
                message: string | null;
            }>
        ) => {
            state.status = action.payload.status;
            state.message = action.payload.message;
        },
        userList: (state: any, action: PayloadAction<User_dao[]>) => {
            state.list = action.payload;
        },
    },
});
export const userList_a = () => {
    return (dispatch: Dispatch, getState: any) => {
        const state = getState();

        if (state.users.list && state.users.list.length <= 0) {
            dispatch(userStatus({ status: PostStatus.loading, message: null }));
            return ajax
                .get("/data/userList.json")
                .then((res: AxiosResponse<User_dao[]>) => {
                    setTimeout(() => {
                        dispatch(
                            userStatus({
                                status: PostStatus.success,
                                message: null,
                            })
                        );
                        const { data } = res;
                        if (data) {
                            dispatch(userList(data));
                        } else {
                            dispatch(userList([]));
                        }
                    }, 2000);
                })
                .catch((error) => {
                    dispatch(
                        userStatus({
                            status: PostStatus.success,
                            message: error.message,
                        })
                    );
                });
        }
    };
};
export const { userStatus, userList } = postSlice.actions;
export default postSlice.reducer;
